//
//  ZDBAddreassViewController.m
//  ZDB
//
//  Created by Kk on 2020/3/17.
//  Copyright © 2020 ZDB. All rights reserved.
//

#import "ZDBAddreassViewController.h"
#import "ZDBAddreassTableViewCell.h"
#import "Addreass.h"
#import "ZDBAddAddreassViewController.h"
@interface ZDBAddreassViewController ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic,strong)NSMutableArray *dataSource;
@property (nonatomic, strong) UITableView * tableView;
@property (nonatomic, strong) UIButton * addBtn;
@property (nonatomic,strong) NoNetworkView * workView;
@end

@implementation ZDBAddreassViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.modelsArry = [NSMutableArray array];
    [self.view addSubview:self.tableView];
    [self.view addSubview:self.addBtn];
    
    
    WEAKSELF
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        STRONGSELFFor(weakSelf);
         [strongSelf getAdressList];
     }];
     [header beginRefreshing];
     self.tableView.mj_header = header;

}

-(void)getAdressList{
  //userAddress_getList
    NSString  * inurl = [[YINetWorkAPIGenerate sharedInstance] APINomark:@"userAddress_getList"];
       WEAKSELF
       [[SmileHttpTool sharedInstance] POST :inurl parameters:nil origin:NO success:^(NSInteger statusCode, NSString *message, id responseObject) {
         STRONGSELFFor(weakSelf)
           
           if (statusCode==0) {
           NSLog(@"integralGoods_GetList----%@",responseObject);
               [strongSelf.modelsArry removeAllObjects];
               strongSelf.modelsArry = [Addreass arrayOfModelsFromDictionaries:[NSArray arrayWithArray:responseObject] error:nil];
           }else{
                [JMNotifyView showNotify:message isSuccessful:NO];
           }
             dispatch_async(dispatch_get_main_queue(), ^{
                           [self placeholderViewWithFrame:self.tableView.frame NoNetwork:NO];
                       });
           // [strongSelf stopLoadingAnimation];
           [strongSelf.tableView reloadData];
           [strongSelf.tableView.mj_header endRefreshing];
       } failure:^(id responseObject, NSError *error) {
           NSLog(@"error----%@",error);
            STRONGSELFFor(weakSelf)
             [strongSelf.tableView.mj_header endRefreshing];
           [JMNotifyView showNotify:@"网络错误，请重试~" isSuccessful:NO];
           // [self stopLoadingAnimation];
       }];

}
- (NSMutableArray *)dataSource
{
    if (!_dataSource) {
        _dataSource = [NSMutableArray new];
    }
    return _dataSource;
}
#pragma  mark -----懒加载
- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, UIScreenWidth, UIScreenHeight  - kStatusBarAndNavigationBarHeight-50)style:UITableViewStylePlain];
        _tableView.tableFooterView = [UIView new];
        _tableView.separatorColor = [UIColor clearColor];
        _tableView.delegate = self;
        _tableView.dataSource=self;
        _tableView.backgroundColor =  VIEWBGCOLOR;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 0.0001)];
        [_tableView registerNib:[UINib nibWithNibName:@"ZDBAddreassTableViewCell" bundle:nil]  forCellReuseIdentifier:@"ZDBAddreassTableViewCell"];
    
    }
    return _tableView;
}
- (UIButton *)addBtn
{
    if (!_addBtn) {
        _addBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, UIScreenHeight-IPhoneBottom -40 - kStatusBarAndNavigationBarHeight, UIScreenWidth, 40)];
        _addBtn.backgroundColor = MAINCOLOR;
        [_addBtn setTitle:@"添加新地址" forState:0];
        _addBtn.titleLabel.font = AutoFont(16);
        [_addBtn setTitleColor:WHITECOLOR forState:0];
        [_addBtn addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _addBtn;
}
- (void)buttonClick:(UIButton *)sender
{
    ZDBAddAddreassViewController * addAddreass = [[ZDBAddAddreassViewController alloc] init];
    addAddreass.title = @"添加地址";
    WEAKSELF
    addAddreass.actionBtnClickBlock = ^(BOOL isSure) {
        STRONGSELFFor(weakSelf);
        [strongSelf.tableView.mj_header beginRefreshing];
    };
    [self.navigationController pushViewController:addAddreass animated:YES];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.modelsArry.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 120;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ZDBAddreassTableViewCell *cell = [_tableView dequeueReusableCellWithIdentifier:@"ZDBAddreassTableViewCell" forIndexPath:indexPath];
    cell.addressModel = self.modelsArry[indexPath.row];
    WEAKSELF
    [cell.defaultBtn add_BtnClickHandler:^(NSInteger tag) { //设置默认地址
      //  cell.defaultBtn.selected =! cell.defaultBtn.selected;
        STRONGSELFFor(weakSelf)
        [strongSelf editTypeAdressRequestAtIndex:indexPath.row];
    }];
    [cell.editBtn add_BtnClickHandler:^(NSInteger tag) {//编辑地址
        STRONGSELFFor(weakSelf)
        ZDBAddAddreassViewController * addAddreass = [[ZDBAddAddreassViewController alloc] init];
        addAddreass.title = @"编辑地址";
        addAddreass.isEdit = YES;
        addAddreass.adsModel =self.modelsArry[indexPath.row];
          addAddreass.actionBtnClickBlock = ^(BOOL isSure) {
              [strongSelf.tableView.mj_header beginRefreshing];
          };
        [strongSelf.navigationController pushViewController:addAddreass animated:YES];
    }];
    [cell.deleteBtn add_BtnClickHandler:^(NSInteger tag) {//编辑地址
        STRONGSELFFor(weakSelf)
        [ strongSelf del_AdressRequestAtIndex:indexPath.row];
    }];

    return cell;
}

-(void)editTypeAdressRequestAtIndex:(NSInteger)indexx{
   Addreass * addressModel = self.modelsArry[indexx];
    //userAddress_addUserAddress
    NSString  * inurl = [[YINetWorkAPIGenerate sharedInstance] APINomark:@"updateUserAddress"];
    NSMutableDictionary * dicc = [NSMutableDictionary dictionary];
    [dicc setValue:addressModel.address forKey:@"address"];
    [dicc setValue:addressModel.name forKey:@"name"];
    [dicc setValue:addressModel.tel forKey:@"tel"];
    if ([addressModel.type integerValue]==2) {
       [dicc setValue:@(1) forKey:@"type"];
    }else{
       [dicc setValue:@(2) forKey:@"type"];
    }
    [dicc setValue:addressModel.province forKey:@"province"];
    [dicc setValue:addressModel.city forKey:@"city"];
    [dicc setValue:addressModel.county forKey:@"county"];
    [dicc setValue:addressModel.way forKey:@"way"];
    [dicc setValue:addressModel.id forKey:@"id"];
       WEAKSELF
       [[SmileHttpTool sharedInstance] POST :inurl parameters:dicc origin:NO success:^(NSInteger statusCode, NSString *message, id responseObject) {
         STRONGSELFFor(weakSelf)
           
           if (statusCode==0) {
           NSLog(@"userAddress_addUserAddress----%@",responseObject);
             [JMNotifyView showNotify:@"保存地址成功" isSuccessful:YES];
               [strongSelf.tableView.mj_header beginRefreshing];

               
           }else{
                [JMNotifyView showNotify:message isSuccessful:NO];
           }
           
       } failure:^(id responseObject, NSError *error) {
           NSLog(@"error----%@",error);
           // STRONGSELFFor(weakSelf)
            
           [JMNotifyView showNotify:@"网络错误，请重试~" isSuccessful:NO];
           // [self stopLoadingAnimation];
       }];
    
    
}
-(void)del_AdressRequestAtIndex:(NSInteger)indexx{
   Addreass * addressModel = self.modelsArry[indexx];
    //userAddress_addUserAddress
    NSString  * inurl = [[YINetWorkAPIGenerate sharedInstance] APINomark:@"Del_deleteUserAddress"];
    NSMutableDictionary * dicc = [NSMutableDictionary dictionary];
    [dicc setValue:addressModel.id forKey:@"id"];
    
       WEAKSELF
       [[SmileHttpTool sharedInstance] POST :inurl parameters:dicc origin:NO success:^(NSInteger statusCode, NSString *message, id responseObject) {
         STRONGSELFFor(weakSelf)
           
           if (statusCode==0) {
           //NSLog(@"userAddress_addUserAddress----%@",responseObject);
             [JMNotifyView showNotify:@"删除地址成功" isSuccessful:YES];
               [strongSelf.modelsArry removeObjectAtIndex:indexx];
               [strongSelf.tableView reloadData];
               
           }else{
                [JMNotifyView showNotify:message isSuccessful:NO];
           }
             
           // [strongSelf stopLoadingAnimation];
           
       } failure:^(id responseObject, NSError *error) {
           NSLog(@"error----%@",error);
           // STRONGSELFFor(weakSelf)
            
           [JMNotifyView showNotify:@"网络错误，请重试~" isSuccessful:NO];
           // [self stopLoadingAnimation];
       }];
    
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
     Addreass * addressModel = self.modelsArry[indexPath.row];
    
    if (self.is_SingleSeclect ==YES) {
        NSLog(@"---addressModel---didSelectRowAtIndexPath");
        if (self.AddreassSeclectBlock) {
             self.AddreassSeclectBlock([addressModel toDictionary]);
         }
        [self.navigationController popViewControllerAnimated:YES];
    }

}


- (void)placeholderViewWithFrame:(CGRect)frame NoNetwork:(BOOL)NoNetwork
{
    if (self.modelsArry.count == 0)
    {
        [_workView removeFromSuperview];
        _workView = [[NoNetworkView alloc] initWithFrame:CGRectMake(0, 0, frame.size.width, frame.size.height) NoNetwork:NoNetwork];
        [self.tableView addSubview:_workView];
        //_workView.centerY = self.collectionView.centerY-100;
    }else
    {
        [_workView dissmiss];
    }
    
}
        
@end
